<?php


declare(strict_types=1);

namespace app\operations\controller\admin;

use app\admin\model\auth\Admin as AdminModel;
use app\operations\model\Brand as BrandModel;
use app\operations\model\Category as CategoryModel;
use app\operations\model\Organ as OrganModel;
use app\operations\model\Store as StoreModel;
use app\shop\model\data\Area as AreaModel;
use sheep\controller\Backend;
use sheep\controller\traits\Crud;
use think\facade\Db;
use think\Request;
use think\Response;
use app\operations\model\Show;
use app\operations\model\CategoryShow;

//商家
class Store extends Backend
{

    use Crud;
    protected $model = null;
    protected $brandModel = null;
    protected $organModel = null;
    protected $adminModel = null;

    protected function initialize()
    {
        $this->model = new StoreModel;
        $this->brandModel = new BrandModel;
        $this->organModel = new OrganModel;
        $this->adminModel = new AdminModel;
    }


    public function qrCode()
    {
        $user = $this->auth()->user();
        $store = $this->model->where('organ_id', $user->organ_id)->where('type', 2)->find();
        if(empty($store)){
            return error('暂无店铺');
        } else {
            $md5 = md5((string) $store->id);
            $text = urlencode("type=bind&store_id=".$store->id."&code=".$md5);
            $url = "https://pageandy.liuliangbenben.top/qrcode/build?text=".$text."&label=&logo=0&labelalignment=center&foreground=%23000000&background=%23ffffff&size=300&padding=10&logosize=50&labelfontsize=14&errorcorrection=medium";
            return success('success', ['url' => $url]);
        }


    }

    /**
     * 商家信息更新
     *
     * @return Response
     */
    public function update(Request $request,$id): Response
    {
        $params = $this->request->only([
            'name','thumb','mobile','longitude','latitude','address','business_rule','status','is_deposit_paid',
            'service_images', 'path_images', 'photo_images', 'per_pay'
        ]);

        $this->svalidate($params);

        $id = intval($id);

        Db::transaction(function () use ($id, $params) {

            $data = $this->model->where('id',$id)->find();
            $data->save($params);

        });

        return success('更新成功');

    }


    /**
     * 商家信息详情
     *
     * @return Response
     */
    public function detail(Request $request,$id): Response
    {

        $detail = $this->model->where('id',$id)->find();

        if(!empty($detail)){
//            $cate = CategoryModel::with(['category' => function($query) {
//                $query->field('id, name');  // 确保包含关联键
//            }])->where('type',$detail['type'])->where('organ_id',$detail['organ_id'])->select()->where('audit_status','normal')->toArray();
//
//            $category_text = [];
//            foreach($cate as $val){
//                $category_text[] = $val['category']['name'];
//            }

            if(!empty($detail)){
                $detail['category_text'] = '宠物行业';
            }

            $detail['business_license'] = AdminModel::where('organ_id',$detail->organ_id)->value('business_license');
        }


        return success('获取成功', $detail);
    }


    /**
     * 编辑(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit(Request $request, $id)
    {
        if (!empty($this->onlyParams)) {                        // 参数过滤
            $params = $request->only($this->onlyParams);
        } else {                                                // 接受全部参数
            $params = $request->param();
        }

        $pk = $this->model->getPk();
        $cutepetDb = Db::connect('mysql_cutepet');
        $result = Db::transaction(function () use ($id, $params, $pk, $cutepetDb) {
            $count = 0;
            foreach ($this->model->whereIn($pk, $id)->cursor() as $row) {
                $params[$pk] = $row->$pk;
                $this->svalidate($params);
                $count += $row->save($params);
                $store = $cutepetDb->name('saas_store')->where('id',$id)->find();
                $insert = $row->toArray();
                $category_ids = Db::name('organ_category')->where('audit_status', 'normal')->where('organ_id', $row->organ_id)->column('category_id');
                $tag = '';
                if(!empty($category_ids)){
                    $show_ids = CategoryShow::where('category_id', 'IN', $category_ids)->column('show_id');
                    $showArray = Show::whereIn('id', $show_ids)->column('name');
                    $tag = implode(',', $showArray);
                }

                $category_tag = $insert['category_tag'];
                if($tag != '') {
                    if(!empty($category_tag)) {
                        $insert['category_tag'] = $tag.','.$category_tag;
                    }else {
                        $insert['category_tag'] = $tag;
                    }
                } else {
                    $insert['category_tag'] = $category_tag;
                }

                unset($insert['type_text']);
                unset($insert['status_text']);
                unset($insert['create_time']);
                unset($insert['update_time']);

                $insert['other_mark'] = '{"医生":"4.7","服务":"4.8","划算":"3.9"}';
                $insert['business_rule'] = '[{"start":"周一","end":"周五","time_begin":"07:00","time_end":"23:00"}]';
                $insert['service_images'] = json_encode($insert['service_images']);
                $insert['path_images'] = json_encode($insert['path_images']);
                $insert['photo_images'] = json_encode($insert['photo_images']);

                $brand = Db::name('shop_brand')->where('organ_id',$row->organ_id)->order('id', 'desc')->find();

                if(!empty($brand)) {
                    $insert['icon'] = $brand['logo'];
                    $insert['brand_name'] = $insert['name'];
                    $insert['intro'] = $brand['remarks'];
                }
                $insert['service_category_ids'] = implode(',', $category_ids);
                //$insert['service_category_ids'] = "1503, 1504, 1505, 1506, 1507, 1508, 1509, 1510, 1511, 1512";
                $nurse = Db::name('nurse')->where('shop_id', $id)->select()->toArray();

                if(!empty($nurse)) {

                    $cutepetDb->name('saas_nurse')->where('shop_id', $id)->delete();
                    $cutepetDb->name('saas_nurse')->insertAll($nurse);
                }
                if(empty($store)) {
                    $params['id'] = $id;
                    $cutepetDb->name('saas_store')->insert($insert);
                } else {
                    unset($insert['id']);
                    $cutepetDb->name('saas_store')->where('id',$id)->update($insert);
                }
            }
            return $count;
        });

        if ($result) {
            return success('更新成功', $result);
        } else {
            return error('更新失败');
        }
    }

    // 热门商圈
    public function hot_area(Request $request)
    {
        $with = ['children.children'];
        $list['district'] = AreaModel::with(['children' => function ($query) {
            $query->field('id, name, pid, level')->where('name', '杭州市')->with('children');
        }])->where(['pid' => 0, 'name' => '浙江省'])->field('id, name, pid, level')->select();

        $list['district_hot_business'] = AreaModel::with(['children' => function ($query) {
            $query->field('id, name, pid, level')->where('name', '杭州市')->with('children');
        }])->where(['pid' => 0, 'name' => '浙江省'])->field('id, name, pid, level')->select();

        $recommend_hot_business = Db::name('shop_additional')->field('attion_id as id, attion_name as name, district_id')->where('is_hot', 1)->select();

        $businessAreasByRegionId = [];
        foreach ($recommend_hot_business as $area) {
            $businessAreasByRegionId[$area['district_id']][] = $area;
        }
        $this->addBusinessAreasToRegions($list['district_hot_business'], $businessAreasByRegionId);

        Db::execute("SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))");
        $list['subway'] = Db::name('city_subway')->field("subway_id as id, count(*), line_no as name")->group('line_no')->order('id', 'asc')->select();
        foreach ($list['subway'] as $key_s => $subways) {
            $subway_data = Db::name('city_subway')->field('subway_id as id, subway_name as name')->where('line_no', $subways['name'])->select();
            $subways['children'] = $subway_data;
            $list['subway'][$key_s] = $subways;
        }

        $list['service_Features'] = $this->model->service_Features();

        return success('获取成功', $list);
    }

    // 递归函数，用于遍历树状结构并添加商圈数据
    private function addBusinessAreasToRegions(&$regions, &$businessAreasByRegionId) {
        foreach ($regions as &$region) {
            if (isset($businessAreasByRegionId[$region['id']])) {
                $region['business_areas'] = $businessAreasByRegionId[$region['id']];
            }
            if (!empty($region['children'])) {
                $this->addBusinessAreasToRegions($region['children'], $businessAreasByRegionId);
            }
        }
    }
}
